<?php


echo '<h2 class="accessibility">'.$this->Lang('select_gateway').'</h2>

<p class="pageoptions">
    <a class="pageoptions" href="'.$actionUrls['install_gateway'].'" title="'.$this->Lang('install_gateway').'">
        <img class="systemicon" src="themes/NCleanGrey/images/icons/system/newobject.gif" alt="'.$this->Lang('install_gateway').'" />
    </a>
    <a class="pageoptions" href="'.$actionUrls['install_gateway'].'" title="'.$this->Lang('install_gateway').'">
        '.$this->Lang('install_gateway').'
    </a>
</p>
';



if(get('gw_id')==''){
	// need to select a gateway to edit
	$gateways = $DB->fetchAll("SELECT * FROM {$this->config['db_prefix']}isubscribe_payment_gateways");

	foreach($gateways as $k=>$v){
	    if($v['is_active']){
            $gateways[$k]['toggleActivateUrl'] = $Antz->addParamsToUrl($actionUrls['config_gateway'], array('deactivate'=>1, 'gw_id'=>$v['id']));
            $gateways[$k]['toggleActivateImg'] = 'themes/NCleanGrey/images/icons/system/true.gif';
            $gateways[$k]['toggleActivateText'] = $this->Lang('deactivate');
        }else{
            $gateways[$k]['toggleActivateUrl'] = $Antz->addParamsToUrl($actionUrls['config_gateway'], array('activate'=>1, 'gw_id'=>$v['id']));
            $gateways[$k]['toggleActivateImg'] = 'themes/NCleanGrey/images/icons/system/false.gif';
            $gateways[$k]['toggleActivateText'] = $this->Lang('activate');
        }
		$gateways[$k]['edit_url'] = $Antz->addParamsToUrl($actionUrls['config_gateway'], array('gw_id'=>$v['id']));
	};
	$this->smarty->assign('gateways', $gateways);

	echo $this->ProcessTemplate('admin.config-gateway.select-gateway.tpl');

}else{
	// lets edit the gateway settings

	$gwId = (int) get('gw_id');
	if($DB->countRows(cms_db_prefix().'isubscribe_payment_gateways', "id = '{$gwId}'")==0){
		Antz::addError('Invalid gateway id');
		Antz::redir($actionUrls['config_gateway']);
	};


    if(get('deactivate')==1){
        $DB->update(cms_db_prefix().'isubscribe_payment_gateways', array('is_active'=>0), "id = '{$gwId}'");
        Antz::redir($actionUrls['config_gateway']);
    };
    if(get('activate')==1){
        $DB->update(cms_db_prefix().'isubscribe_payment_gateways', array('is_active'=>1), "id = '{$gwId}'");
        Antz::redir($actionUrls['config_gateway']);
    };
    


	$gwData = $DB->fetchRow("SELECT * FROM {$this->config['db_prefix']}isubscribe_payment_gateways WHERE id = '{$gwId}'");

	$gwObj = unserialize($CRYPT->decrypt($gwData['obj']));

	if(!is_object($gwObj) || !($gwObj instanceof ISubscribe_Payment_Gateway)){
		if(!Antz_IntelliForm::submitted('conf-gateway', false)) Antz::addError($this->Lang('critical_error_gateway_not_loaded'));
		$gwObj = new $gwData['class_name'];
	};

	if(Antz_IntelliForm::submitted('conf-gateway')){
		$error = false;

		$title = post('title');
		$isActive = (int) post('isActive');
		$desc = post('desc', '', 5000);

		if(trim($title)==''){
			$error = true;
			Antz::addFormError('title');
		};
		if(trim($desc)==''){
			$error = true;
			Antz::addFormError('desc');
			Antz::addError($this->Lang('no_description'));
		};

		$settings = $gwObj->getConfigAsArray();

		foreach($settings as $k=>$v){
			if(isset($v['hidden']) && (bool) $v['hidden']) continue;
			if(isset($v['maxlength']) && $v['maxlength']>0) $maxlength = (int) $v['maxlength'];
			else $maxlength = 255;
			$settings[$k]['value'] = post('IS_'.$v['key'], '', $maxlength);
		};

		if(!$error){

			// first, lets see if the settings are accepted by the gateway object
			if(!$gwObj->setConfig($settings)){
				Antz::addError($this->Lang('there_were_errors').implode('<br />', $gwObj->getErrorsAsArray()));
				$formErrors = $gwObj->getFormErrorsAsArray();
				foreach($formErrors as $key=>$message){
					Antz::addFormError('IS_'.$key, $message);
				};
				$error = true;
			};
			if(!$error){
				// ok then, lets save the object and all settings
				$dbParams = array(
					'title' => $title,
					'description' => $desc,
					'is_active' => $isActive,
					'obj' => $CRYPT->crypt(serialize($gwObj))
				);
				$DB->update(cms_db_prefix().'isubscribe_payment_gateways', $dbParams, "id = '{$gwId}'");
				Antz::addSuccess($this->Lang('config_gateway_success'));
				Antz::redir($actionUrls['config_gateway']);
			};
		};


	}

	$form = Antz::newObject('Antz_Form', 'conf-gateway');
	$form->setAction($Antz->addParamsToUrl($actionUrls['config_gateway'], array('gw_id'=>$gwId)));
	$block = $form->add('full');

	// general settings for all gateways
	$fs = $block->add($this->Lang('general_settings'));

	$fs->addInput('text', 'title', $this->Lang('title'), post('title', $gwData['title']))->addClass('wide');
	// don't allow the gateway name to be changed...
	//$fs->addInput('text', 'className', 'Class name', post('className', $gwData['class_name']));
	$txt = $fs->addInput('textarea', 'desc', $this->Lang('desc'), post('desc', $gwData['description']));
	$txt->setId('ISgwdesc');
	$mces = explode(',', $_SESSION['tiny_live_textareas']);
	if(!in_array('ISgwdesc', $mces)) $mces[] = 'ISgwdesc';
	$_SESSION['tiny_live_textareas'] = implode(',', $mces);
	$chk = $fs->addCheckboxGroup('isActive');
	$chk->add('isActive', $this->Lang('is_active'), '1', (bool) post('isActive', $gwData['is_active']));


	$settings = $gwObj->getConfigAsArray();

	if(count($settings)>0){
		// add gateway specific configuration parameters, defined in $gatewayObj->config
		$fs = $block->add($this->Lang('gateway_specific_settings'));
		foreach($settings as $k=>$v){

			if(isset($v['hidden']) && (bool) $v['hidden']) continue;

			if($v['type']=='tinymce'){
				// make a tinymce editable field
				$txt = $fs->addInput('textarea', 'IS_'.$v['key'], $v['title'], $v['value']);
				$txt->setId('IS_'.$v['key']);
				if(isset($v['class']) && $v['class']!='') $txt->addClass($v['class']);
				$mces = explode(',', $_SESSION['tiny_live_textareas']);
				if(!in_array('IS_'.$v['key'], $mces)) $mces[] = 'IS_'.$v['key'];
				$_SESSION['tiny_live_textareas'] = implode(',', $mces);
			}elseif($v['type']=='select'){
				// make a select drop menu

				if(count($v['options'])==0){
					// no options exist for the drop menu
					$fs->addLongTag('p', $this->Lang('error_no_options'));
				}else{
					// lets make a drop menu
					$sel = $fs->addSelect($v['key'], $v['title'], $v['value']);
					$sel->add($this->Lang('please_select'));
					foreach($v['options'] as $optKey=>$optVal){
						$sel->add($optVal, $optKey);
					};
					if(isset($v['id']) && $v['id']!='') $sel->setId($v['id']);
					if(isset($v['class']) && $v['class']!='') $sel->addClass($v['class']);
				};

			}elseif($v['type']=='text' || $v['type']=='textarea' || $v['type']=='longtag'){
				// make an input of type text, textarea or longtag
				$input = $fs->addInput($v['type'], 'IS_'.$v['key'], $v['title'], $v['value']);
				if(isset($v['id']) && $v['id']!='') $input->setId($v['id']);
				if(isset($v['class']) && $v['class']!='') $input->addClass($v['class']);
			}else{
				// add an error because developer is using an unsupported type
				$fs->addLongTag('p', $this->Lang('error_gateway_config_types'));
			};
		};
	};

	// our submit button!
	$fs->addInput('submit', 'submitBtn', '&nbsp;', $this->Lang('update'));

	echo $form->render();
}



